package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.utils.ResultUtil;
import com.cpit.platform.config.UploadPathConfig;
import com.cpit.platform.log.LogOperator;
import com.cpit.qualitycontrol.entity.ApkUpload;
import com.cpit.qualitycontrol.service.ApkUploadService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.http.HttpHeaders;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping(value = "/apk")
public class ApkUploadController {

    private static final String loggerName = ApkUploadController.class.getName();

    private final ResourceLoader resourceLoader;

    @Autowired
    public ApkUploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Autowired
    private ApkUploadService apkUploadService;

    @Autowired
    private UploadPathConfig uploadPath;

    @ApiOperation(value="上传android apk 版本", notes="上传 android apk 版本")
    @ApiImplicitParam(name = "apkUpload", value = "apkUpload对象", required = true, dataType = "ApkUpload")
    @ResponseBody
    @RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
    public Result<ApkUpload> addAndSubmitAppeal(@RequestBody ApkUpload apkUpload) {

        apkUpload = apkUploadService.versionRelease(apkUpload);

        return ResultUtil.<ApkUpload>success(apkUpload);
    }

    @ApiOperation(value="获取android apk 最新版本", notes="获取android apk 最新版本，无参数")
    @ResponseBody
    @RequestMapping(value = {"/queryLatestVersion"}, method = RequestMethod.POST)
    public Result<ApkUpload> queryLatestVersion() {

        ApkUpload apkUpload = apkUploadService.queryLatestVersion();

        return ResultUtil.<ApkUpload>success(apkUpload);
    }

    @ApiOperation(value="下载android apk 最新版本", notes="下载android apk 最新版本，无参数")
    @ResponseBody
    @RequestMapping(value = {"/download/android-apk"}, method = RequestMethod.GET)
    public ResponseEntity<?> downloadLastApkFile() {

        try {
            ApkUpload apkUpload = apkUploadService.queryLatestVersion();

            String fileDirPath = uploadPath.getApk();
            String fileName = apkUpload.getFilepath();
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

            LogOperator.debug(loggerName, "fileDirPath:" + fileDirPath + ",fileName:" + fileName);

            Path filePath = Paths.get(fileDirPath, fileName);
            FileSystemResource file = new FileSystemResource(filePath.toFile());

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    String.format("attachment; filename=\"%s\"", java.net.URLEncoder.encode("qc.apk", "UTF-8")));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(resourceLoader.getResource("file:" + filePath));
        } catch (Exception e) {
            LogOperator.err(loggerName, "download file error!", e);
            return ResponseEntity.notFound().build();
        }
    }

}